import type { ValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  personInChargeEnum,
  patrolStateEnum,
  deptTreeSelectEnum
} from '~/store/oam/tour/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElCard, ElFormItem, ElSelect, ElOption, ElSpace, ElLink, ElDatePicker } from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import TourRecordInfo from './info'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'

export default defineComponent(function plan() {
  const route = useRoute()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const recordRef = ref<ValuesType>()
  const tourState = useVuexGetters('tour', [
    'personInChargeOpt',
    'patrolStateOpt',
    'deptTreeSelectOpt'
  ])
  const store = useStore()
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '巡视分组名称',
      prop: 'groupName',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '巡视类型',
      prop: 'type',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '任务结束周期',
      prop: 'taskEndTime',
      minWidth: 220
    },
    {
      label: '所属工区',
      prop: 'workAreaName',
      showOverflowTooltip: true,
      minWidth: 140
    },
    {
      label: '巡视开始时间',
      prop: 'beginTime',
      minWidth: 220
    },
    {
      label: '巡视结束时间',
      prop: 'endTime',
      minWidth: 220
    },
    {
      label: '区域数量',
      prop: 'assetCounts',
      minWidth: 160,
      align: 'center'
    },
    {
      label: '责任人',
      prop: 'leadUserName',
      minWidth: 160
    },
    {
      label: '巡视结果',
      prop: 'resultState',
      minWidth: 160,
      render: (_, value) => {
        return <>{value === 2 ? '发现缺陷' : '正常'}</>
      }
    },
    {
      label: '巡视状态',
      prop: 'status',
      minWidth: 160,
      render: (_, value) => {
        return <>{completeStatus(value)}</>
      }
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 160,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => infoOpen(row)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情
          </ElLink>
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    store.dispatch('tour/GetPatrolHandleUser')
    store.dispatch('tour/WorkareaSelectList')
    store.dispatch('tour/GetPatrolState', 'patrol_record_status')
    const res = await store.dispatch('user/GetCurrentTenant')
    if (res.code === 200) {
      window.localStorage.setItem('userinfo', JSON.stringify(res.data))
    }

    if (route.query.id) infoOpen({ id: route.query.id as string })
  })

  const completeStatus = (value: any) => {
    switch (value) {
      case 1:
        return '进行中'
        break
      case 2:
        return '已完成'
        break
      case 3:
        return '已超时'
        break
    }
  }
  //  详情
  const infoOpen = (row?: ValuesType) => {
    recordRef.value = row
    // router.push({ path: '/oam/tour/record/info', query: { id: row?.id } })
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          proSaasTableRef.value!?.toSearch()
        }, 100)
      }
    }
    if (recordRef.value?.id) {
      return <TourRecordInfo id={recordRef.value.id} goBack={() => infoOpen(undefined)} />
    }

    return (
      <ElCard>
        <ProSaasTable<ValuesType>
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{
            deliverDate: undefined,
            beginTime: formValues.deliverDate?.[0],
            endTime: formValues.deliverDate?.[1]
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="tour/GetPatrolRecordList"
          searchformResponsiveCol={[
            <ElFormItem key="leadUserId" prop="leadUserId" label="">
              <ElSelect
                v-model={formValues.leadUserId}
                clearable
                onChange={clearSearchTable}
                placeholder="责任人"
              >
                {tourState.personInChargeOpt?.value?.map((item: personInChargeEnum) => (
                  <ElOption key={item?.id} label={item?.realName} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="workAreaId" prop="workAreaId" label="">
              <ElSelect
                v-model={formValues.workAreaId}
                clearable
                onChange={clearSearchTable}
                placeholder="所属工区"
              >
                {tourState.deptTreeSelectOpt?.value?.map((item: deptTreeSelectEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="status" prop="status" label="">
              <ElSelect
                v-model={formValues.status}
                clearable
                onChange={clearSearchTable}
                placeholder="巡视状态"
              >
                {tourState.patrolStateOpt?.value?.map((item: patrolStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="deliverDate" prop="deliverDate" label="">
              <ElDatePicker
                v-model={formValues.deliverDate}
                start-placeholder="巡视开始日期"
                end-placeholder="巡视结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="daterange"
                {...props}
              />
            </ElFormItem>
          ]}
        ></ProSaasTable>
      </ElCard>
    )
  }
})
